<!DOCTYPE HTML>
<title>Tests that we don't garbage collect audio object while it is still playing.</title>
<script src="../resources/gc.js"></script>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script>
// According to http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html,
// 4.8.10.8 Playing the media resource,
// Media elements must not stop playing just because all references to them have
// been removed; only once a media element is in a state where no further audio
// could ever be played by that element may the element be garbage collected.
// see https://bugs.webkit.org/show_bug.cgi?id=66878, https://bugs.webkit.org/show_bug.cgi?id=70421,
// and http://crbug.com/62604 for more details).
async_test(function(t) {
    var audioPlayers = 4;
    var playedCount = 0;
    var audioFile = "content/silence.oga";
    var audio = new Audio(audioFile);

    audio.onended = t.step_func(function() {
        playedCount ++;
        if (playedCount <= audioPlayers) {
            audio.currentTime = audio.duration - 0.35;
            audio.play();
            if (playedCount == audioPlayers) {
                audio = null;
                gc();
            }
        } else {
            t.done();
        }
    });

    audio.oncanplaythrough = t.step_func(function() {
        audio.oncanplaythrough = null;
        audio.currentTime = audio.duration - 0.35;
        audio.play();
    });
});
</script>